package com.fh.controller.system.appuser;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.http.ProtocolType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.push.model.v20160801.PushNoticeToAndroidRequest;
import com.aliyuncs.push.model.v20160801.PushNoticeToAndroidResponse;
import com.aliyuncs.push.model.v20160801.PushRequest;
import com.aliyuncs.push.model.v20160801.PushResponse;
import com.aliyuncs.utils.ParameterHelper;
import com.fh.controller.base.BaseController;
import com.fh.entity.Page;
import com.fh.entity.ProjectStateEnum;
import com.fh.entity.system.Account;
import com.fh.entity.system.Project;
import com.fh.entity.system.Role;
import com.fh.entity.system.Unfundproject;
import com.fh.service.system.appuser.AppUserProjectService;
import com.fh.service.system.appuser.AppuserService;
import com.fh.service.system.role.RoleService;
import com.fh.util.Const;
import com.fh.util.Jurisdiction;
import com.fh.util.Logger;
import com.fh.util.MD5;
import com.fh.util.ObjectExcelView;
import com.fh.util.PageData;
import com.fh.util.StringUtil;

@Controller
@RequestMapping(value="/appuser")
@SuppressWarnings("unused")
public class AppProjectController extends BaseController{
	protected Logger logger = Logger.getLogger(this.getClass());
	String menuUrl = "appuser/listProjects.do"; //菜单地址(权限用)
	@Resource(name="appuserService")
	private AppuserService appuserService;
	@Resource(name="appUserProjectService")
	private AppUserProjectService  appUserProjectService;
	@Resource(name="roleService")
	private RoleService roleService;
	
	@RequestMapping(value="project")
	public ModelAndView getProjects(Page page) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			
			String user_id = pd.getString("user_id");
			
			if(null != user_id && !"".equals(user_id)){
				user_id = user_id.trim();
				pd.put("user_id", user_id);
			}
			page.setPd(pd);
			/*去查找用户项目*/
			List<PageData>	userProjectList = appUserProjectService.findAllProject(page);			//列出用户列表
			mv.setViewName("system/appuser/project_list");
			mv.addObject("pd", pd);
			mv.addObject("statelist", ProjectStateEnum.toList());
			mv.addObject("userProductList", userProjectList);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
		return mv;
		
	}
	/*
	 * 搜索项目
	 * 
	 */
	@RequestMapping(value="/searchproject")
	public ModelAndView listProject(Page page)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		
		String USERNAME = pd.getString("USERNAME");
		
		String auditStateValue=pd.getString("auditstatevalue");
		if(null != auditStateValue && !"".equals(auditStateValue)){
			auditStateValue = auditStateValue.trim();
			pd.put("auditStateValue", auditStateValue);
		}
		if(null != USERNAME && !"".equals(USERNAME)){
			USERNAME = USERNAME.trim();
			pd.put("USERNAME", USERNAME);
		}
		
		String lastLoginStart = pd.getString("lastLoginStart");
		String lastLoginEnd = pd.getString("lastLoginEnd");
		
		if(lastLoginStart != null && !"".equals(lastLoginStart)){
			lastLoginStart = lastLoginStart;
			pd.put("lastLoginStart", lastLoginStart);
		}
		if(lastLoginEnd != null && !"".equals(lastLoginEnd)){
			lastLoginEnd = lastLoginEnd;
			pd.put("lastLoginEnd", lastLoginEnd);
		} 
		
		page.setPd(pd);
		List<PageData>	userList = appUserProjectService.searchProject(page);			//列出用户列表
		
		mv.setViewName("system/appuser/project_list");
		mv.addObject("userProductList", userList);
		mv.addObject("statelist", ProjectStateEnum.toList());
		mv.addObject("pd", pd);
		return mv;
	}
	
	/**
	 * 搜索用户
	 * <p>Title: listUsers</p>
	 * <p>Description: </p>
	 * @param page
	 * @return
	 * @throws Exception
	 */
	
	@RequestMapping(value="/searchuser")
	public ModelAndView listUsers(Page page)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		
		String USERNAME = pd.getString("USERNAME");
		
		if(null != USERNAME && !"".equals(USERNAME)){
			USERNAME = USERNAME.trim();
			pd.put("USERNAME", USERNAME);
		}
		
		String lastLoginStart = pd.getString("lastLoginStart");
		String lastLoginEnd = pd.getString("lastLoginEnd");
		
		if(lastLoginStart != null && !"".equals(lastLoginStart)){
			lastLoginStart = lastLoginStart;
			pd.put("lastLoginStart", lastLoginStart);
		}
		if(lastLoginEnd != null && !"".equals(lastLoginEnd)){
			lastLoginEnd = lastLoginEnd;
			pd.put("lastLoginEnd", lastLoginEnd);
		} 
		
		page.setPd(pd);
		List<PageData>	userList = appUserProjectService.searchUser(page);			//列出用户列表
		mv.setViewName("system/appuser/appuser_list");
		mv.addObject("userList", userList);
		mv.addObject("pd", pd);
		return mv;
	}
	
	@RequestMapping(value="listProjects")
	public ModelAndView getUserProjects(Page page) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			
			String user_id = pd.getString("user_id");
			
			if(null != user_id && !"".equals(user_id)){
				user_id = user_id.trim();
				pd.put("user_id", user_id);
			}
			
			page.setPd(pd);
			/*去查找用户项目*/
			List<PageData>	userProjectList = appUserProjectService.listAllUserProject(page);			//列出用户列表
			mv.setViewName("system/appuser/appuserproject_list");
			mv.addObject("pd", pd);
			mv.addObject("statelist", ProjectStateEnum.toList());
			mv.addObject("userProductList", userProjectList);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
		return mv;
		
	}
	
	
	@RequestMapping(value="listuseraccount")
	public ModelAndView getUserAccount(Page page) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			
			String user_id = pd.getString("user_id");
			
			if(null != user_id && !"".equals(user_id)){
				user_id = user_id.trim();
				pd.put("user_id", user_id);
			}
			
			page.setPd(pd);
			//去查找用户账户
			List<PageData> userRecordList=null; 
			List list=new ArrayList<>();
			List<Account> userAccountList = appUserProjectService.listAllUserAccount(page);
			for(int i=0;i<userAccountList.size();i++){
				
					Long account_id=userAccountList.get(i).getId();
					pd.put("account_id", account_id);
					userRecordList=appUserProjectService.listAllUserRecord(pd);
				list.addAll(userRecordList);
			}
			
			if(list!=null||list.size()!=0){
				if(user_id!=null&&user_id!=""){
					pd.put("user_id", user_id);
					List<PageData> accountList = appUserProjectService.findAccountByUid(pd);
					mv.addObject("accountList", accountList);
				}
			}
			
			//列出用户列表
			mv.setViewName("system/appuser/appuserrecord_list");
			mv.addObject("pd", pd);
			mv.addObject("recordList", list);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
		return mv;
		
	}
	
	
	@RequestMapping(value="/goEditRecord")
	public ModelAndView goEditRecord(Page page){
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		String id = pd.getString("Recrord_ID");
		String USER_ID = pd.getString("USER_ID");
		pd.put("USER_ID", USER_ID);
		try {
			/*pd = appuserService.findByUiId(pd);	//根据ID读取
*/
			pd.put("id", id);
			
			List<Role> roleList = roleService.listAllappERRoles();			//列出所有二级角色
			List<PageData> record = appUserProjectService.findRecordByIdAndUid(pd);
			
			mv.setViewName("system/appuser/appuserrecord_edit");
			mv.addObject("msg", "saverecord");
			mv.addObject("record", record);
			mv.addObject("roleList", roleList);
										//根据ID读取
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}
	@RequestMapping(value="/goEditProject")
	public ModelAndView goEditProject(){
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			
			List<PageData> project = appUserProjectService.findProjectById(pd);
			List<Role> roleList = roleService.listAllappERRoles();			//列出所有二级角色
			/*pd = appuserService.findByUiId(pd);*/								//根据ID读取
			mv.setViewName("system/appuser/appuserproject_edit");
			mv.addObject("msg", "editproject");
			mv.addObject("pd", pd);
			mv.addObject("roleList", roleList);
			mv.addObject("project", project);
			mv.addObject("statelist", ProjectStateEnum.toList());
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}
	/**
	 * 修改项目进度
	 */
	@RequestMapping(value="/editproject")
	public ModelAndView editProject(PrintWriter out) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		
		if(pd.getString("auditstatevalue").equals("3")&&pd.getString("auditStateDesc") != null && !"".equals(pd.getString("auditStateDesc"))){
			pd.put("auditStateDesc", pd.getString("auditStateDesc"));
		}
		else{
			pd.put("auditStateDesc", "");
		}
		appUserProjectService.editProject(pd);
		//查找项目对应的用户Id
		String project_id=(pd.getString("id"));
		
		if(project_id!=null&&project_id!=""){
			pd.put("project_id", project_id);
			List<PageData> project=appUserProjectService.getUserIdByProId(pd);
			if(project!=null&&project.size()>0){
				PushNoticeToAll(project.get(0).getString("user_id"),project.get(0).getString("project_name"));
			}
		}
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}
	
	
	/**
	 * 修改奖励记录
	 */
	@RequestMapping(value="/saverecord")
	public ModelAndView editRecord(PrintWriter out) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		
		if(pd.getString("recordDesc") != null && !"".equals(pd.getString("recordDesc"))){
			pd.put("recordDesc", pd.getString("recordDesc"));
		}
		appUserProjectService.editRecord(pd);
		
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}
	
	
	
	/**
	 * 新增奖励记录
	 */
	@RequestMapping(value="/addrecord")
	public ModelAndView addRecord(PrintWriter out) throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		
		if(pd.getString("recordDesc") != null && !"".equals(pd.getString("recordDesc"))){
			/*String projectName=pd.getString("project_name");
			Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
            String dateString = formatter.format(currentTime);
			String recordDesc="您的"+projectName+"项目于"+dateString+"获得"+pd.getString("recordDesc");*/
			
			pd.put("recordDesc", pd.getString("recordDesc"));
		}
		appUserProjectService.addRecord(pd);
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 新增用户奖励记录展示页面
	 * <p>Title: goAddRecord</p>
	 * <p>Description: </p>
	 * @return
	 */
	@RequestMapping(value="/goAddRecord")
	public ModelAndView goAddRecord(){
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		String user_id=pd.getString("user_id");
		
		try {
			if(user_id!=null&&user_id!=""){
				pd.put("user_id", user_id);
				/*List<PageData> userProject=appUserProjectService.findUserProjectListByUserId(pd);
				
				if(userProject!=null&&userProject.size()==0){
					mv.addObject("project", "1");//区分无项目
				}
				else{
					mv.addObject("project", "2");//区分有项目
					mv.addObject("userProject", userProject);
				}*/
				List<PageData> accountList = appUserProjectService.findAccountByUid(pd);
				List<Role> roleList = roleService.listAllappERRoles();			//列出所有二级角色
				mv.setViewName("system/appuser/appusergoaddrecord_add");
				if(accountList==null||accountList.size()==0){
					mv.addObject("account", "1");//区分无账户
				}
				else{
					mv.addObject("account", "2");//区分有账户
					mv.addObject("msg", "addrecord");
					mv.addObject("pd", pd);
					mv.addObject("roleList", roleList);
					mv.addObject("accountList", accountList);
				}
				
			}
			
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}
	
	/**
     * 推送通知给android
     * <p>
     * 参见文档 https://help.aliyun.com/document_detail/48087.html
     */
    
    
	public void PushNoticeToAll( String userId,String projectName){
    	try {
    	IClientProfile profile = DefaultProfile.getProfile(Const.accessPro, Const.accessKeyId, Const.accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        PushRequest pushRequest = new PushRequest();
        // 推送目标
        pushRequest.setAppKey(24760409l);
        pushRequest.setTarget("ACCOUNT"); 
        pushRequest.setTargetValue(userId);//推送目标: DEVICE:按设备推送 ALIAS : 按别名推送 ACCOUNT:按帐号推送  TAG:按标签推送; ALL: 广播推送
        pushRequest.setPushType("NOTICE"); // 消息类型 MESSAGE NOTICE
        pushRequest.setDeviceType("ALL"); // 设备类型 ANDROID iOS ALL.
        // 推送配置
        pushRequest.setTitle("晟融通"); // 消息的标题
        pushRequest.setBody("您的:"+projectName+"项目有新状态"); // 消息的内容
        // 推送配置: iOS
        pushRequest.setIOSBadge(1); // iOS应用图标右上角角标
        pushRequest.setIOSMusic("default"); // iOS通知声音
        pushRequest.setIOSSubtitle("");//iOS10通知副标题的内容
        pushRequest.setIOSNotificationCategory("iOS10 Notification Category");//指定iOS10通知Category
        pushRequest.setIOSMutableContent(true);//是否允许扩展iOS通知内容
        pushRequest.setIOSApnsEnv("DEV");//iOS的通知是通过APNs中心来发送的，需要填写对应的环境信息。"DEV" : 表示开发环境 "PRODUCT" : 表示生产环境
        pushRequest.setIOSRemind(true); // 消息推送时设备不在线（既与移动推送的服务端的长连接通道不通），则这条推送会做为通知，通过苹果的APNs通道送达一次。注意：离线消息转通知仅适用于生产环境
        pushRequest.setIOSRemindBody("iOSRemindBody");//iOS消息转通知时使用的iOS通知内容，仅当iOSApnsEnv=PRODUCT && iOSRemind为true时有效
        // 推送配置: Android
        pushRequest.setAndroidNotifyType("NONE");//通知的提醒方式 "VIBRATE" : 震动 "SOUND" : 声音 "BOTH" : 声音和震动 NONE : 静音
        pushRequest.setAndroidNotificationBarType(1);//通知栏自定义样式0-100
        pushRequest.setAndroidNotificationBarPriority(1);//通知栏自定义样式0-100
        pushRequest.setAndroidOpenType("ACTIVITY"); //点击通知后动作 "APPLICATION" : 打开应用 "ACTIVITY" : 打开AndroidActivity "URL" : 打开URL "NONE" : 无跳转
        //pushRequest.setAndroidOpenUrl("http://www.aliyun.com"); //Android收到推送后打开对应的url,仅当AndroidOpenType="URL"有效
        pushRequest.setAndroidActivity("com.srt.shengrongtong.MainActivity"); // 设定通知打开的activity，仅当AndroidOpenType="Activity"有效
        pushRequest.setAndroidMusic("default"); // Android通知音乐
        /*pushRequest.setAndroidPopupActivity("com.ali.demo.PopupActivity");//设置该参数后启动辅助弹窗功能, 此处指定通知点击后跳转的Activity（辅助弹窗的前提条件：1. 集成第三方辅助通道；2. StoreOffline参数设为true）
        pushRequest.setAndroidPopupTitle("Popup Title");
        pushRequest.setAndroidPopupBody("Popup Body");*/
        // 推送控制
        Date pushDate = new Date(System.currentTimeMillis()) ; // 30秒之间的时间点, 也可以设置成你指定固定时间
        String pushTime = ParameterHelper.getISO8601Time(pushDate);
        pushRequest.setPushTime(pushTime); // 延后推送。可选，如果不设置表示立即推送
        String expireTime = ParameterHelper.getISO8601Time(new Date(System.currentTimeMillis() + 12 * 3600 * 1000)); // 12小时后消息失效, 不会再发送
        pushRequest.setExpireTime(expireTime);
        pushRequest.setStoreOffline(true); // 离线消息是否保存,若保存, 在推送时候，用户即使不在线，下一次上线则会收到
        PushResponse pushResponse = client.getAcsResponse(pushRequest);
        String msg=pushResponse.getRequestId()+ pushResponse.getMessageId();
        if(msg!=null){
        	 logBefore(logger,"sucess"+msg);
        }
        else{
        	 logBefore(logger,"fail"+msg);
        }
        /*logBefore(logger,"消息推送"+pushResponse.getRequestId(), pushResponse.getMessageId());
        System.out.printf("RequestId: %s, MessageID: %s\n",
        pushResponse.getRequestId(), pushResponse.getMessageId());*/
    	} catch (Exception e) {
			// TODO: handle exception
    		e.printStackTrace();
		}
    }
	
	
	/*
	 * 导出用户信息到EXCEL
	 * @return
	 */
	@RequestMapping(value="/excel")
	public ModelAndView exportExcel(Page page){
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try{
				//检索条件===
				String USERNAME = pd.getString("USERNAME");
				if(null != USERNAME && !"".equals(USERNAME)){
					USERNAME = USERNAME.trim();
					pd.put("USERNAME", USERNAME);
				}
				String lastLoginStart = pd.getString("lastLoginStart");
				String lastLoginEnd = pd.getString("lastLoginEnd");
				if(lastLoginStart != null && !"".equals(lastLoginStart)){
					lastLoginStart = lastLoginStart+" 00:00:00";
					pd.put("lastLoginStart", lastLoginStart);
				}
				if(lastLoginEnd != null && !"".equals(lastLoginEnd)){
					lastLoginEnd = lastLoginEnd+" 00:00:00";
					pd.put("lastLoginEnd", lastLoginEnd);
				} 
				//检索条件===
				
				Map<String,Object> dataMap = new HashMap<String,Object>();
				List<String> titles = new ArrayList<String>();
				
				titles.add("股票代码/企业名称"); 		//1
				titles.add("企业方联系人");  		//2
				titles.add("项目进度");			//3
				titles.add("联系人职务");			//4
				titles.add("项目详情");			//5
				titles.add("企业需求");			//6
				titles.add("经营方式");		//7
				 
				
				dataMap.put("titles", titles);
				/*去查找用户项目*/
				page.setPd(pd);
				List<PageData>	userProjectList = appUserProjectService.findAllProject(page);			//列出用户列表
				 
				List<PageData> varList = new ArrayList<PageData>();
				for(int i=0;i<userProjectList.size();i++){
					PageData vpd = new PageData();
					String state="";
					/*if(userProjectList.get(i).getString("audit_state")==list.){
						
					}*/
					vpd.put("var1", userProjectList.get(i).getString("stock_code"));		//1
					vpd.put("var2", userProjectList.get(i).getString("link_man"));		//2
					vpd.put("var3", ProjectStateEnum.getEnum(Integer.parseInt(userProjectList.get(i).getString("audit_state"))).getDesc());			//3
					vpd.put("var4", userProjectList.get(i).getString("link_type"));	//4
					vpd.put("var5", userProjectList.get(i).getString("instruction"));		//5
					vpd.put("var6", userProjectList.get(i).getString("requertment"));		//6
					vpd.put("var7", userProjectList.get(i).getString("work_type"));	//7
					varList.add(vpd);
				}
				dataMap.put("varList", varList);
				ObjectExcelView erv = new ObjectExcelView();					//执行excel操作
				mv = new ModelAndView(erv,dataMap);
			 
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	
}
